package net.begincode.SSO.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 开放的拦截接口，获取当前登录状态，返回ticket
 * @author Administrator
 *
 */
public class ClientFilter implements Filter {
	public static final String LOGIN_PAGE_URL = "http://localhost:8080/SSO-web/core/login.jsp";
	private String loginPageUrl;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		  loginPageUrl = filterConfig.getInitParameter("loginPageUrl")==null?LOGIN_PAGE_URL:filterConfig.getInitParameter("loginPageUrl");
	}

	@Override
	public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) sRequest;
		HttpServletResponse response = (HttpServletResponse) sResponse;
		String backURL = request.getParameter("backURL");
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			for(Cookie cookie:cookies){
				if("ticket".equals(cookie.getName())){
					cookie.setMaxAge(60*30);
					cookie.setPath("/");
					response.addCookie(cookie);
					response.sendRedirect(backURL+"?ticket="+cookie.getValue());
					return;
				}
			}
		}
		response.sendRedirect(loginPageUrl+"?backURL="+backURL);
		return;
	}

	@Override
	public void destroy() {

	}

}
